package com.durian.base.frame.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.durian.base.frame.easyrouter.EasyRouter;

/**
 * 说明：懒加载Fragment
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2016/6/16 13:31
 * <p/>
 * 版本：version 1.0
 */
public abstract class BaseLazyFragment extends SupportFragment {

    private boolean  isLazyLoad = false;
    private boolean  mIsFirstVisible = true;

    @Override
    protected void onInitCreateView(View view) {
        super.onInitCreateView(view);
        if (openARouter()) {
            EasyRouter.inject(this);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isNewLazyVersion()){
            boolean isVis = isHidden() || getUserVisibleHint();
            if (isVis && mIsFirstVisible) {
                onFirstUserVisible();
                mIsFirstVisible = false;
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isNewLazyVersion()){
            if (!hidden) {
                onUserVisible();
            } else {
                onUserInvisible();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isNewLazyVersion()){
            if (isVisibleToUser) {
                onUserVisible();
            } else {
                onUserInvisible();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isNewLazyVersion()){
            if (!isLazyLoad){
                onFirstUserVisible();
                isLazyLoad = true;
            }else {
                onUserVisible();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isNewLazyVersion()){
            onUserInvisible();
        }
    }

    protected boolean isNewLazyVersion(){
        return false;
    }

    /**
     * 说明：第一次界面可见调用
     */
    protected abstract void onFirstUserVisible();

    /**
     * 说明：界面可见调用
     */
    protected void onUserVisible() {
        if (!isNewLazyVersion()){
            if (mIsFirstVisible && isResumed()) {
                onFirstUserVisible();
                mIsFirstVisible = false;
            }
        }
    }

    /**
     * 说明：界面不可见调用
     */
    protected abstract void onUserInvisible();


    /**
     * 打开arouter注入，默认打开
     *
     * @return
     */
    protected boolean openARouter() {
        return true;
    }

}
